package com.tg.paw.common.mq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tg.paw.common.annotation.SysLog;
import com.tg.paw.common.mq.entity.MqMessage;
import com.tg.paw.common.mq.entity.MqMessageLog;
import com.tg.paw.common.mq.service.IMqMessageLogService;
import com.tg.paw.common.mq.service.IMqMessageService;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.common.util.MessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 消息 前端控制器
 * </p>
 *
 * @author Rubble
 * @since 2020-06-19
 */
@RestController
@Slf4j
@Api(tags = "消息管理API", value = "ApiMqMessageController")
@RequestMapping("/mqMessage")
public class ApiMqMessageController {
    @Autowired
    private IMqMessageService mqMessageService;
    @Autowired
    private IMqMessageLogService mqMessageLogService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @SysLog(MODULE = "oms", REMARK = "发送消息")
    @ApiOperation("发送消息")
    @GetMapping(value = "/send/{id}")
    public CommonResult updateMqMessage(@ApiParam("消息id") @PathVariable Long id) {

        try {
            MqMessage message = mqMessageService.getById(id);
            if(message==null){
                return CommonResult.failed("消息不存在.messageId:"+id);
            }
            MqMessageLog messageLog = MessageUtil.buildMessageLog(message);
            rabbitTemplate.convertAndSend(message.getExchange(),message.getRoutingKey(),message.getMessageBody());
            // 重发后删除  非正常消费会重新记录消息 uid相同
            mqMessageService.removeById(id);
            messageLog.setRemark("重新发送");
            mqMessageLogService.save(messageLog);
        } catch (Exception e) {
            log.error("发送消息：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.success();
    }

    @SysLog(MODULE = "oms", REMARK = "根据uid获取消息")
    @ApiOperation("根据uid获取消息")
    @GetMapping(value = "/{uid}")
    public CommonResult getMessageByUid(@ApiParam("消息uid") @PathVariable Long uid) {

        LambdaQueryWrapper<MqMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MqMessage::getUuid,uid);
        List<MqMessage> messageList = mqMessageService.list(queryWrapper);

        return CommonResult.success(messageList);
    }


}
